package com.peaksport.pkms.permit.service;

import java.math.BigDecimal;
import java.security.MessageDigest;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.peaksport.framework.base.dao.IBaseDAO;
import com.peaksport.framework.base.service.CoreBaseService;
import com.peaksport.framework.exception.PKBizException;
import com.peaksport.framework.util.PKPublicUtils;
import com.peaksport.pkms.basedata.master.entity.AdminOrgEntity;
import com.peaksport.pkms.permit.dao.UserDAO;
import com.peaksport.pkms.permit.entity.PermItemEntity;
import com.peaksport.pkms.permit.entity.UserEntity;

import sun.misc.BASE64Encoder;

@Service
public class SSOService extends CoreBaseService{
	
	@Autowired
	private UserDAO userDao;
	
	/**
	 * 登录检验
	 * @param userNum 用户账号
	 * @param password 密码
	 * @return
	 */
	public UserEntity login(String userNum, String password) {
		StringBuffer sql = new StringBuffer();
		sql.append("select FId,FName_l2,FNumber,FPassword,FIsDelete,FIsLocked,FForbidden,")
				.append("FIsBizAdmin,FSupplierId,FCustomerId,FPersonId ")
				.append("from t_pm_user where fnumber='").append(userNum).append("'");
		UserEntity userEntity = (UserEntity)queryOneRecordForNative(sql.toString(), UserEntity.class);
		if (userEntity == null) {
			throw new PKBizException(String.format("不存在用户[%s]",userNum));
		}
		String userId = userEntity.getId();
		String dbPwd = userEntity.getPassword();
		String encodePwd = encodePassword(userId, password);
		if (!PKPublicUtils.equals(dbPwd,encodePwd)) throw new PKBizException("密码不正确.");
		if (userEntity.isDelete()) throw new PKBizException("账号已被删除");
		if (userEntity.isLocked()) throw new PKBizException("账号已被锁定,请稍后再试或联系系统管理员.");
		if (userEntity.isForbidden()) throw new PKBizException("账号已被禁用");
		return userEntity;
		
	}

	/**
	 * 检查是否有功能权限
	 * @param userId 用户Id
	 * @param orgId  组织Id
	 * @param permItemId 权限项目Id
	 */
	public boolean checkFuncPerm(String userId, String orgId, String permItemId) {
		verifyDevNull(userId,"用户userId不能为空");
		verifyDevNull(orgId,"组织orgId不能为空");
		verifyDevNull(permItemId,"权限项permItemId不能为空");
		
		String sqlUser = "select FID,FNumber,FName_l2 from t_pm_user where fid='"+userId+"'";
		UserEntity userEntity = (UserEntity)queryOneRecordForNative(sqlUser, UserEntity.class);
		verifyBizNull(userEntity,"不存在用户ID[%s]",userId);
		String sqlOrg = "select FNumber,FName_l2 from t_org_admin where fid='" + orgId + "'";
		AdminOrgEntity adminOrgEntity = (AdminOrgEntity)queryOneRecordForNative(sqlOrg, AdminOrgEntity.class);
		verifyBizNull(adminOrgEntity, "不存在行政组织ID[%s]", orgId);
		String sqlPermItem = "select FNumber,FAlias_L2 from t_pm_permItem where fid='" + permItemId + "'";
		PermItemEntity permItemEntity = (PermItemEntity)queryOneRecordForNative(sqlPermItem, PermItemEntity.class);
		verifyBizNull(permItemEntity, "不存在权限项ID[%s]", permItemId);
		
		
		StringBuffer sql = new StringBuffer();
		sql.append("select sum(cnt) cnt from (select count(1) cnt from t_pm_userorgperm a ")
		.append(String.format(" where a.fowner='%s' and a.forgid='%s' and a.fpermitemid='%s'",userId,orgId,permItemId))
		.append(" union all ")
		.append("select count(1) cnt from t_pm_userroleorg a ")
		.append("left join t_pm_roleperm aa on aa.froleid=a.froleid ")
		.append(String.format("where a.fuserid='%s' and a.forgid='%s' and aa.fpermitemid='%s')", userId,orgId,permItemId)) ;  
		BigDecimal obj  = queryOneValueForNative(sql.toString(),BigDecimal.class);
		boolean b =  obj != null && obj.intValue() > 0;
		if (!b) {
			throw PKBizException.throwException("用户[%s]没有组织[%s]的[%s]权限", userEntity.getName(),adminOrgEntity.getName(),permItemEntity.getAlias());
		}
		return b;
	}
	
	@Transactional
	private void savetest(UserEntity userEntity) {
		UserEntity u = new UserEntity();
		u.setName("匹克");
		u.setNumber("pkms");
		userDao.save(u);
	}
	
	/**
	 * 密码EAS加密方式
	 * @param userId 用户Id
	 * @param password 密码
	 * @return
	 */
	private String encodePassword(String userId, String password) {
		String strSrc = userId + password;
		byte btKey[] = new byte[strSrc.getBytes().length + 1];
		System.arraycopy(strSrc.getBytes(), 0, btKey, 0, strSrc.getBytes().length);
		String strEncode;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(btKey);
			byte btDigest[] = md.digest();
			BASE64Encoder encoder = new BASE64Encoder();
			strEncode = encoder.encode(btDigest);
			return strEncode;
		} catch (Exception e) {
			return "notpasswodsuccc";
		}
	}

	@Override
	public IBaseDAO<?> getDAO() {
		// TODO Auto-generated method stub
		return null;
	}


}
